<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.ID" placeholder="订单号" class="filter-item search-input" clearable />
      <el-input v-model="listQuery.mobile" placeholder="手机号" class="filter-item search-input" clearable prop="mobile" />
      <el-input v-model="listQuery.title" placeholder="线路关键词" class="filter-item search-input" clearable />
      <el-date-picker
        v-model="listQuery.startTime"
        placeholder="下单时间（开始）"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        class="filter-item search-input"
      />
      <el-date-picker
        v-model="listQuery.endTime"
        placeholder="下单时间（结束）"
        type="datetime"
        value-format="yyyy-MM-dd HH:mm:ss"
        class="filter-item search-input"
      />
      <el-select
        v-model="listQuery.status"
        placeholder="订单状态"
        clearable
        style="width: 120px"
        class="filter-item search-input"
      >
        <el-option
          v-for="item in [
            {label:'待支付', value:'1'},
            {label:'已支付', value:'2'},
            {label:'已出团', value:'3'},
            {label:'申请退款', value:'4'},
            {label:'退款成功', value:'5'},
            {label:'已取消', value:'6'},
            {label:'已核销', value:'12'},
          ]"
          :key="item.value"
          :label="item.label.trim()"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.peerId"
        placeholder="所属分公司"
        clearable
        style="width: 190px"
        class="filter-item search-input"
      >
        <el-option v-for="item in peerOptions" :key="item.peerId" :label="item.name" :value="item.peerId" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">
        导出
      </el-button>
      <!--      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">-->
      <!--        添加-->
      <!--      </el-button>-->
    </div>

    <el-table
      :key="tableKey + 1"
      v-loading="listLoading2"
      :data="peerStockList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="peerName + '-核销库存'" min-width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" min-width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stock }}</span>
        </template>
      </el-table-column>
    </el-table>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="订单号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderId.split("_")[0] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" min-width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ row.orderUserName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="线路名称" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ row.lineName }}</span>
        </template>
      </el-table-column>
      <el-form-item label="出发城市" prop="startCity">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ getCityLabel(row.startCity) }}</span>
        </template>
      </el-form-item>
      <el-table-column label="金额" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出行人数" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" min-width="152px" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ row.orderTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款时间" min-width="152px" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ row.payTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出行时间（选完更新）" min-width="180px" align="center">
        <template slot-scope="{row}">
          <el-date-picker
            :id="row.ID"
            v-model="row.outTime"
            placeholder="出行时间"
            value-format="yyyy-MM-dd"
            type="date"
            class="filter-item search-input"
            style="width: 150px"
            @change="refundTimeChange"
            @focus="refundTimeFocus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="核销/退款时间" min-width="152px" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ row.doneTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" min-width="152px" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ orderStatus(row) }}

            <el-button v-if="row.status === '已支付' && userIsTotal" size="mini" type="primary" @click="orderStatusChange(row, '')">退款</el-button>
            <el-button v-if="row.status === '已出团' && userIsTotal" size="mini" type="primary" @click="orderStatusChange(row, '')">未核销</el-button>
            <span v-if="row.status === '已出团' && userIsTotal">| 退款</span>

            <el-button v-if="row.status === '待支付' && !userIsTotal" size="mini" type="primary" @click="orderStatusChange(row, '')">未付款</el-button>
            <span v-if="row.status === '待支付' && !userIsTotal"> | 未出行 | 未核销</span>

            <el-button v-if="row.status === '已支付' && !userIsTotal" size="mini" type="primary" @click="orderStatusChange(row, '')">未出行</el-button>
            <span v-if="row.status === '已支付' && !userIsTotal"> | 未核销</span>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!--    <pagination-->
    <!--      v-show="total>0"-->
    <!--      :total="total"-->
    <!--      :page.sync="listQuery.page"-->
    <!--      :limit.sync="listQuery.limit"-->
    <!--      @pagination="getList"-->
    <!--    />-->
  </div>
</template>

<script>
import { changeOutTime, changeStatus, list, peerStock } from '@/api/order'
import { listSelection, listStartCity } from '@/api/selectOptions'
import { confirm, csvExport, getLabelByValue, toSelectOptions } from '@/utils/common'
// import Pagination from '@/components/Pagination'

export default {
  components: {
    // Pagination
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      peerStockList: null,
      total: 0,
      listLoading: true,
      listLoading2: true,
      userIsTotal: false,
      listQuery: {
        ID: undefined,
        mobile: undefined,
        title: undefined,
        startTime: undefined,
        endTime: undefined,
        status: undefined,
        peerId: '1',
        csv: undefined // 为1时，导出
      },
      peerName: '武汉分公司',
      startCityOptions: undefined,
      peerOptions: undefined,
      rules: {
        mobile: [{ required: true, message: '电话号不能为空', trigger: 'change' }]
      },
      changeStatusData: {
        ID: undefined,
        status: undefined,
        stock: undefined,
        lineId: undefined
      },
      refundTimeChangeData: {
        ID: undefined,
        outTime: undefined
      }
    }
  },
  created() {
    this.getStartCityOptions()
    this.getPeerOptions()
    this.getList()
    this.getPeerStockList()
  },
  methods: {
    refundTimeFocus(row) {
      this.refundTimeChangeData.ID = row.orderId
    },
    refundTimeChange(date) {
      this.refundTimeChangeData.outTime = date
      changeOutTime(this.refundTimeChangeData).then(response => {
        for (let i = 0; i < this.list.length; ++i) {
          if (this.list[i].ID === this.refundTimeChangeData.ID) {
            this.list[i] = this.refundTimeChangeData.outTime
            break
          }
        }
        this.$notify({
          title: '更新成功',
          message: '更新出行时间成功！',
          type: 'success',
          duration: 2000
        })
      })
    },
    orderStatus(row) {
      let res = ''
      // 用户是否为总公司
      if (this.userIsTotal) {
        switch (row.status) {
          case '待支付':
            res = '未付款 | 未出行 | 未核销 | 退款'
            break
          case '已支付':
            res = '已付款 | 未出行 | 未核销 | '
            break
          case '已出团':
            res = '已付款 | 出行中 | '
            break
          case '退款成功':
            res = '已付款 | 未出行 | 未核销 | 已退款'
            break
          case '已核销':
            res = '已付款 | 出行中 | 已核销 | 退款'
            break
        }
      } else {
        switch (row.status) {
          case '待支付':
            res = ''
            break
          case '已支付':
            res = '已付款 | '
            break
          case '已出团':
            res = '已付款 | 出行中 | 未核销'
            break
          case '退款成功':
            res = '已付款 | 未出行 | 已退款'
            break
          case '已核销':
            res = '已付款 | 出行中 | 已核销 '
            break
        }
      }
      return res
    },
    orderStatusChange(row) {
      let confirmMsg = ''
      switch (row.status) {
        case '待支付':
          confirmMsg = '确认将该笔订单状态改为已付款吗？'
          break
        case '已支付':
          if (this.userIsTotal) {
            confirmMsg = '确认退款该笔订单？'
          } else {
            confirmMsg = '确认将该笔订单状态改为出行中吗？'
          }
          break
        case '已出团':
          confirmMsg = '确认核销该笔订单？'
          break
      }
      confirm(this, confirmMsg, () => {
        this.changeStatusData.ID = row.orderId
        this.changeStatusData.status = row.status
        // 获取线路库存和线路ID
        this.changeStatusData.lineId = getLabelByValue(this.peerStockList, row.lineName, 'lineId', 'title')
        this.changeStatusData.stock = getLabelByValue(this.peerStockList, row.lineName, 'stock', 'title')
        changeStatus(this.changeStatusData).then(response => {
          let msg = ''
          // 修改当前页面库存数
          for (let i = 0; i < this.peerStockList.length; ++i) {
            if (this.peerStockList[i].lineId === this.changeStatusData.lineId) {
              switch (row.status) {
                case '待支付':
                  this.peerStockList[i].stock -= 1
                  msg = '该笔订单状态改为已付款，某某线路库存数减1'
                  break
                case '已支付':
                  this.peerStockList[i].stock += 1
                  if (this.userIsTotal) {
                    msg = '该笔订单状态已改为出行中。'
                  } else {
                    msg = '该笔订单状态改为已付款，某某线路库存数加1。'
                  }
                  break
                case '已出团':
                  msg = '该笔订单状态已改为已核销。'
                  break
              }
              break
            }
          }
          this.$notify({
            title: '成功',
            message: msg,
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    getPeerOptions() {
      listSelection().then(response => {
        this.peerOptions = response.data
      })
    },
    getCityLabel(value) {
      return getLabelByValue(this.startCityOptions, value)
    },
    getPeerStockList() {
      this.listLoading2 = true
      peerStock(this.listQuery).then(response => {
        this.peerStockList = response.data
        this.listLoading2 = false
        this.peerName = getLabelByValue(this.peerOptions, this.listQuery.peerId, 'name', 'peerId')
      })
    },
    getList() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data
        this.listLoading = false
      })
    },
    getStartCityOptions() {
      listStartCity().then(response => {
        this.startCityOptions = toSelectOptions(response.data)
      })
    },
    handleFilter() {
      const mobileReg = /^[1][3,4,5,7,8][0-9]{9}$/
      if (this.listQuery.mobile === undefined || mobileReg.test(this.listQuery.mobile)) {
        this.getList()
        this.getPeerStockList()
      } else {
        this.$notify({
          title: '查询失败',
          message: '请输入正确格式的手机号！',
          type: 'error',
          duration: 2000
        })
      }
    },
    handleExport() {
      list(Object.assign(this.listQuery, { csv: 1 }), 'arraybuffer').then(response => {
        csvExport(response)
        this.listQuery.csv = 0
      })
    }
  }
}
</script>

<style>
.search-input {
  width: 150px;
  margin-right: 15px;
}
</style>
